package com.dhecp.project.system.controller;

import java.util.*;

import com.dhecp.core.layui.*;
import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.core.constant.ModuleTable;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.core.controller.BaseController;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.system.domain.SysDictionaryForModule;
import com.dhecp.project.system.domain.SysMenuInfo;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import com.dhecp.project.system.service.SysMenuInfoService;

/**
 * 菜单信息 控制层
 * @author lwl
 * @version 2019年11月1日
 */
@Controller
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController{
    private String prefix = "system/menu";
    private String moduleTable = ModuleTable.MENU_INFO;

    @Autowired
    private SysMenuInfoService menuInfoService;
    
    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;
    
    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    @Autowired
    private TreeDataUtil treeDataUtil;

    @Autowired
    private TreeSelectDataUtil treeSelectDataUtil;

    @RequiresPermissions("system:menu:view")
    @GetMapping()
    public ModelAndView menuList(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
    	params.put("entity", new SysMenuInfo()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
    	
    	Subject userSubject = ShiroUtils.getSubject();
    	Integer toolBarWidth = 0;
    	if (userSubject.isPermitted("system:menu:add")){	//当前登录用户主体是否有添加的权限
        	//params.put("checkBox", "yes"); //生成表格gridColumns时包含复选
        	toolBarWidth = toolBarWidth + 320;
    	}
    	if (userSubject.isPermitted("system:menu:edit")){ //当前登录用户主体是否有修改的权限
    		toolBarWidth = toolBarWidth + 100;
    	} 
    	if (userSubject.isPermitted("system:menu:delete")){ //当前登录用户主体是否有删除的权限
    		toolBarWidth = toolBarWidth + 100;
    	}
    	params.put("toolBarWidth", toolBarWidth);
    	
    	ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        try{
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.setViewName(prefix + "/menu");
        return mv;
    }

    @GetMapping("/menu_select")
    public ModelAndView menuSelect(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        mv.setViewName(prefix + "/menu_select");
        return mv;
    }
    
    /**
     * 查询所有菜单信息
     * @param params
     * @return TableDataInfo
     * @author lwl
     */
    @RequiresPermissions("system:menu:list")
    @RequestMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
        startPage();
        List<SysMenuInfo> menuList = new ArrayList<SysMenuInfo>();
		try {
			menuList = menuInfoService.queryMenuInfo(params);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return getDataTable(menuList);
    }

    /**
     * 查询功能和菜单信息
     * @param menuType： 可选参数【功能设置(menuType=ByModuleSet)，仅拥有功能的菜单和功能(menuType=ByModule)，手机端菜单和功能(menuType=ByAppModule)，全部已启用的菜单(menuType=ByAllActive)，全部菜单(menuType=ByAll)】
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions("system:menu:list")
    @RequestMapping("/listtreejson")
    @ResponseBody
    public Object menuInfoTreeJson(@RequestParam Map<String, Object> params){
        if (params.get("menuType") == null || params.get("menuType") == ""){
            //菜单类型（menuType）：功能设置(menuType=ByModuleSet)，仅拥有功能的菜单和功能(menuType=ByModule)，手机端菜单和功能(menuType=ByAppModule)，全部已启用的菜单(menuType=ByAllActive)，全部菜单(menuType=ByAll)
            params.put("menuType", "ByModule");
        }
        List<TreeDataModel> treeDataModelList = new ArrayList<TreeDataModel>();
        try{
            treeDataModelList = menuInfoService.queryMenuInfoTree(params);
            treeDataModelList = treeDataUtil.dealTreeDataModel(treeDataModelList,treeDataModelList.get(0).getMaxlevels());
        }catch(Exception e){
            return treeDataModelList;
        }
        return treeDataModelList;
    }
    
    /**
     * 查询功能和菜单信息
     * @param menuType： 可选参数【功能设置(menuType=ByModuleSet)，仅拥有功能的菜单和功能(menuType=ByModule)，手机端菜单和功能(menuType=ByAppModule)，全部已启用的菜单(menuType=ByAllActive)，全部菜单(menuType=ByAll)】
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions("system:menu:list")
    @RequestMapping("/listtreeselectjson")
    @ResponseBody
    public Object menuInfoTreeSelectJson(@RequestParam Map<String, Object> params){
        if (params.get("menuType") == null || params.get("menuType") == ""){
            //菜单类型（menuType）：功能设置(menuType=ByModuleSet)，仅拥有功能的菜单和功能(menuType=ByModule)，手机端菜单和功能(menuType=ByAppModule)，全部已启用的菜单(menuType=ByAllActive)，全部菜单(menuType=ByAll)
            params.put("menuType", "ByModule");
        }
        List<TreeSelectDataModel> treeSelectDataModelList = new ArrayList<TreeSelectDataModel>();
        try{
            treeSelectDataModelList = menuInfoService.queryMenuInfoSelectTree(params);
            for(TreeSelectDataModel treeSelectDataModel : treeSelectDataModelList){
                Map<String,String> checkArr = new LinkedHashMap<String,String>();
                checkArr.put("type", "0");
                checkArr.put("checked", "0");
                treeSelectDataModel.setCheckArr(checkArr);
            }
            treeSelectDataModelList = treeSelectDataUtil.dealTreeSelectDataModel(treeSelectDataModelList,treeSelectDataModelList.get(0).getMaxlevels());
        }catch(Exception e){
            return treeSelectDataModelList;
        }
        return treeSelectDataModelList;
    }
    
    /**
     * 查询用户手机分组功能菜单
     * @param params
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions("system:menu:list")
    @RequestMapping("/mobilemenulist")
    @ResponseBody
    public Map<String, List<SysDictionaryForModule>> mobileMenuInfoList(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
        List<SysDictionaryForModule> menuList = new ArrayList<SysDictionaryForModule>();
        List<SysDictionaryForModule> cMenuList = new ArrayList<SysDictionaryForModule>();
        Map<String, List<SysDictionaryForModule>> menu = new LinkedHashMap<String, List<SysDictionaryForModule>>();
        String menuKey = "";
		try {
			menuList = menuInfoService.queryMobileMenuInfoList(params);
			for(SysDictionaryForModule dictionaryForModule : menuList){
				if ("".equals(menuKey) || !menuKey.equals(dictionaryForModule.getMobileGroup())){
					if(!"".equals(menuKey)){
						menu.put(menuKey, cMenuList);
					}
					cMenuList = new ArrayList<SysDictionaryForModule>();
					menuKey = dictionaryForModule.getMobileGroup();
				}
				cMenuList.add(dictionaryForModule);
			}
			menu.put(menuKey, cMenuList);	//循环结束后添加最后一组功能
		} catch (Exception e) {
			e.printStackTrace();
		}
        return menu;
    }
    
    /**
     * 打开新增菜单信息页面
     * @param params
     * @return ModelAndView
     * @author lwl
     */
    @RequiresPermissions("system:menu:add")
    @GetMapping("/add")
    public ModelAndView add(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        try{
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("pageType","add");
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.setViewName(prefix + "/menu_add");
        return mv;
    }
    
    /**
     * 新增菜单信息——数据提交
     * @param params
     * @return AjaxResult
     * @author lwl
     */
    @Log(title = "菜单保存", businessType = BusinessType.INSERT)
    @RequiresPermissions("system:menu:add")
    @PostMapping("/addpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult addSave(@RequestParam Map<String, Object> params){
    	AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= menuInfoService.insertMenu(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     * 打开菜单信息修改页面
     * @param params
     * @return ModelAndView
     * @author lwl
     */
    @RequiresPermissions("system:user:edit")
    @GetMapping("/edit")
    public ModelAndView menuInfoEdit(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        SysMenuInfo menuInfo= new SysMenuInfo();
        mv = this.gotoModelAndViewErrorPage(params, "guid", "菜单编号");
        if (mv.isEmpty()){
            try{
                dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
                if (dictionaryForFieldMap.isEmpty()){
                    ajaxResult = AjaxResult.error("未获取到字段属性。");
                }else{
                	menuInfo = menuInfoService.queryMenuInfoByGuid(params.get("guid").toString());
                	if (menuInfo == null){
                		ajaxResult = AjaxResult.error("没有查到菜单。");
                	}else{
                    	ajaxResult = AjaxResult.success("数据获取成功。");
                	}
                }
            }
            catch(Exception e){
                ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
            }
            mv.addObject("pageType","edit");
            mv.addObject("menuInfo",menuInfo);
            mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
            mv.addObject("ajaxResult", ajaxResult);
            mv.setViewName(prefix + "/menu_add");
        }
        return mv;
    }

    /**
     * 修改菜单信息--数据提交
     * @param params
     * @return AjaxResult
     * @author lwl
     */
    @Log(title = "菜单修改", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:menu:edit")
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editSave(@RequestParam Map<String, Object> params){
    	AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= menuInfoService.updateMenu(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     * 删除菜单信息
     * @param params
     * @return AjaxResult
     * @author lwl
     */
    @RequiresPermissions("system:menu:delete")
    @Log(title = "删除菜单", businessType = BusinessType.DELETE)
    @PostMapping("/delete")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult delete(@RequestParam Map<String, Object> params){
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= menuInfoService.deleteMenuByGuid(params);
        }catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     * 加载所有菜单列表树
     */
    @GetMapping("/menuTreeData")
    @ResponseBody
    public List<TreeDataModel> menuTreeData(Map<String, Object> params){
        List<TreeDataModel> ztrees = menuInfoService.queryMenuInfoTree(params);
        return ztrees;
    }
    
    /**
     * 选择菜单树
     */
    @RequiresPermissions("system:menu:view")
    @GetMapping("/selectMenuTree")
    public ModelAndView selectMenuTree(Map<String, Object> params){	
    	ModelAndView mv = this.getModelAndView();
        mv.setViewName(prefix + "/menu_tree");	
        return mv;
    }
    
    /**
     * 选择菜单图标
     */
    @GetMapping("/icon")
    public String icon(){
        return prefix + "/icon";
    }

}